<template>
  <u-form-item
    :label="label"
    :label-width="labelWidth"
    :prop="props.data.field"
    :required="props.data.required"
    :rules="props.data.rules"
  >
    <u-checkbox-group
      v-model="val"
      placement="column"
      :readonly="props.data.readonly"
      :disabled="props.data.disabled || props.data.readonly"
      @change="onChange"
    >
			<view v-for="(item, index) in options" :key="index" class="__check">
				<u-checkbox
					:key="index"
					:label="item"
					:name="item"
				>
				</u-checkbox>
			</view>
    </u-checkbox-group>
  </u-form-item>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useProps } from '../hooks/props'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const { label, labelWidth } = useProps(props)
const val = ref()

const options = computed(() => {
  const opts = props.data.options
  if (opts) {
    return opts.split('\n')
  } else {
    return []
  }
})

watch(
  () => props.data.defaultVal,
  () => {
    if (props.data.defaultVal) {
      val.value = props.data.defaultVal.split(',')
      emits('valueChange', { name: props.data.field, value: props.data.defaultVal })
    }
  },
  { immediate: true }
)

const onChange = (_val: any[]) => {
  const data = props.data
  data.defaultVal = _val.join(',')
  emits('valueChange', { name: props.data.field, value: data.defaultVal })
}
</script>

<style lang="scss" scoped>
.__check {
	padding: 10rpx 15rpx;
	border: 1px solid $u-border-color;
	&:not(:last-child){
		border-bottom: 0;
	}
	&:first-child {
		border-top-left-radius: 4px;
		border-top-right-radius: 4px;
	}
	&:last-child {
		border-bottom-left-radius: 4px;
		border-bottom-right-radius: 4px;
	}
}
</style>

